//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "tools\fn_spawnVehicle.sqf"
#include <tmf_constants.h>
#include <tmf_macros.h>

TRACE_1("Start",_this);
TMFPROFILERSTART;

private ["_result","_unit","_units","_grp","_pos","_type","_init","_azi","_sim","_veh","_skill","_crew_list","_instance_id"];
DEFAULT_PARAM(_instance_id,0,TMF_SERVER_INSTANCE_ID);
DEFAULT_PARAM(_type,1,"");
DEFAULT_PARAM(_grp,2,grpNull);
DEFAULT_PARAM(_pos,3,ARR_3(0,0,0));
DEFAULT_PARAM(_dist,4,0);
DEFAULT_PARAM(_init,5,[]);
DEFAULT_PARAM(_azi,6,0);
DEFAULT_PARAM(_skill,7,([] call FFUNC(getUnitSkill)));
DEFAULT_PARAM(_crew_list,8,[]);

if (_instance_id == "") then { _instance_id = TMF_SERVER_INSTANCE_ID; };

_result = [];

if (!IS_ARRAY(_pos)) then {
	if (AND_ALSO(IS_STRING(_pos),IS_MARKER(_pos))) then {
		if (_dist <= 0) then {
			_dist = ((markerSize _pos) select 0) max ((markerSize _pos) select 1);
		};
		_pos = markerPos _pos;
	} else {
		_pos = [];
	};
};
if (!IS_SCALAR(_dist)) then { _dist = 0 };
if (!IS_SCALAR(_skill)) then { _skill = ([] call FFUNC(getUnitSkill)) };
if (!IS_SCALAR(_azi)) then { _azi = 0 };

if (!IS_ARRAY(_crew_list)) then { _crew_list = [] };
if (AND_ALSO(count _crew_list > 0,!IS_STRING((_crew_list select 0)))) then { _crew_list = [] };
if (AND_ALSO(count _crew_list > 1,!IS_ARRAY((_crew_list select 1)))) then { _crew_list = [] };

if (IS_STRING(_type) && { (_type isKindof "AllVehicles") } && {(count _pos >= 2)}) then {
	_grp = [_grp] call FFUNC(createGroup);
	if ((count _pos) == 2) then {_pos set [count _pos, 0]};	
	_sim = toLower(getText(configFile >> "CfgVehicles" >> _type >> "simulation"));
	DEBUG_1("Simulation",_sim);
	_is_air = (_sim in ["airplane", "helicopter","helicopterx","airplanex","helicopterrtd"] && (_pos select 2) > 0);
	if (_is_air) then {
		_veh = [_instance_id, _type, _pos, [], _dist, "FLY"] call FFUNC(createVehicle);
		_veh setPos _pos;
		_veh engineOn true;
		if (_dist <= 0) then { _veh setPos _pos; };
		_veh setDir _azi;
		_veh setVelocity [50 * (sin _azi), 50 * (cos _azi), 0];
	} else {
		_veh = [_instance_id, _type, _pos, [], _dist, "NONE"] call FFUNC(createVehicle);
		if (_dist <= 0) then { _veh setPos _pos; };
		_veh setDir _azi;
	};

	if ((getNumber(configFile >> "CfgVehicles" >> _type >> "ARTY_IsArtyVehicle")) == 1) then {
		TLOG_1("It's an arty vehicle!!",_type);
	};

	_grp addVehicle _veh;
	_crew = [_instance_id,_veh, _grp, _skill, _init, false, "", _crew_list] call FFUNC(spawnCrew);
	//_veh engineOn true;

	_result = [_veh, _crew, _grp];
} else {
	ERROR_1("Invalid Parameters",_this);
};
TRACE_1("End",_result);
TMFPROFILERSTOP;
_result